<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>JSP</title>
    <!-- Bootstrap core CSS -->
    <link href="/css/bootstrap.css" rel="stylesheet">

</head>

<body>
<!-- 用户更新模态框-->
<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">员工更新</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="from_modal_update">
                    <div class="form-group">
                        <label for="empName_add_input" class="col-sm-2 control-label">用户名</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empName_static_p"></p>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="password_update_input" class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <input style="width: 40%" type="text" class="form-control" name="password" id="password_update_input"
                                   placeholder="密码">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" style="width: 50%" class="form-control" name="email" id="email_update_input"
                                   placeholder="邮箱">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="type_update_input" class="col-sm-2 control-label">用户类型</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="type" id="type_update_input" value=1>管理员
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="type" id="type1_update_input" value=2>普通用户
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="status_update_input" class="col-sm-2 control-label">用户状态</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="status" id="status_update_input" value=1>解除黑名单
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="status" id="status1_update_input" value=2>黑名单
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="phone_update_input" class="col-sm-2 control-label">电话号码</label>
                        <div class="col-sm-10">
                            <input type="text" style="width: 50%" class="form-control" name="phoneNum" id="phone_update_input"
                                   placeholder="电话号码">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="credit_update_input" class="col-sm-2 control-label">积分</label>
                        <div class="col-sm-10">
                            <input type="text" style="width: 20%" class="form-control" name="credit" id="credit_update_input"
                                   placeholder="积分">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
            </div>
        </div>
    </div>
</div>

<!-- 用户添加模态框-->
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">用户添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="from_modal_add">
                    <div class="form-group">
                        <label for="empName_add_input" class="col-sm-2 control-label">用户名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="username" id="empName_add_input"
                                   placeholder="用户名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="password_add_input" class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="password" id="password_add_input"
                                   placeholder="密码">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">用户类型</label>
                        <div class="checkbox text-left">
                            <label>
                                <input type="radio" id="admin" name="type" value=1>管理员
                            </label>
                            <label>
                                <input type="radio" id="user" name="type" value=2 checked>普通用户
                            </label>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="email" id="email_add_input"
                                   placeholder="邮箱">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">区号</label>
                        <div class="col-sm-10" style="width: 40%;">
                            <select class="form-control" id="" name="phoneNum">
                                <option value="86">+86</option>
                                <option value="85">+85</option>
                                <option value="84">+84</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">电话号码</label>
                        <div class="col-sm-10" style="width: 40%;">
                            <input type="tel" class="form-control" id="phone_add_input" name="phoneNum" required="required">
                        </div>
                        <span class="help-block"></span>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>



    <!-- 右边主显示部分 -->
    <div class="main-rightbox">
        <div class="mainrightbox">
            <!-- 显示表格 -->
            <div class="main_box">
                <!-- 表格显示区域 -->
                <div style="padding-left: 0%;margin: 0px;margin: 0px">
                    <!--标题-->
                    <div style="float: left" class="col-md-12">
                        <h4>用户列表</h4>
                    </div>
                    <!--按钮-->
                    <div class="row" style="margin-bottom: 1%">
                        <div class="col-md-4 col-md-offset-8">
                            <button class="btn btn-primary" id="emp_add_modal_btn">新增</button>
                            <button class="btn btn-danger" id="emp_delete_btn">删除</button>
                            <a class="btn btn-default" href="/user/admin">返回</a>
                        </div>
                    </div>
                    <!---表格内容-->
                    <div class="row">
                        <div class="col-md-12">
                            <table class="table table-hover" id="emps_table">
                                <thead>
                                <tr>
                                    <th>
                                        <input type="checkbox" id="checkbox_all"/>
                                    </th>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>邮箱</th>
                                    <th>电话号码</th>
                                    <th>积分</th>
                                    <th>状态</th>
                                    <th>用户类型</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>

                                </tbody>

                            </table>

                        </div>

                    </div>

                    <!--导航上下页-->
                    <div class="row" style="padding-top: 1px">
                        <div class="col-md-6" id="page_info_area"></div>
                        <div class="col-md-6" id="page_nav_area"></div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
</div>

<!-- 引入公共js文件 -->
<script src="/js/jquery-3.3.1.min.js"></script>
<script src="/js/bootstrap.js"></script>

<script type="text/javascript">

    var totalRescord, currentPage, totalPages;

    $(function () {
        toPage(1);
    });

    function toPage(pn) {

        $.ajax({
            url: "/get/users",
            data: "pn=" + pn,
            type: "GET",
            success: function (result) {
                build_emps_table(result);
                build_page_info(result);
                build_page_nav(result);
            }
        });
    }

    //显示分析条
    function build_page_nav(result) {

        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>")
            .append($("<a></a>")
                .append("首页"));
        var prePageLi = $("<li></li>")
            .append($("<a></a>")
                .append("&laquo;"));
        if (result.extend.pageInfo.hasPreviousPage == false) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        } else {
            //为首页前一页添加单击事件
            firstPageLi.click(function () {
                toPage(1)
            });
            prePageLi.click(function () {
                toPage(result.extend.pageInfo.pageNum - 1);
            });

        }

        var nextPageLi = $("<li></li>")
            .append($("<a></a>")
                .append("&raquo;"));

        var lastPageLi = $("<li></li>")
            .append($("<a></a>")
                .append("末页"));
        if (result.extend.pageInfo.hasNextPage == false) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        } else {
            //为末页和后一页添加点击事件
            nextPageLi.click(function () {
                toPage(result.extend.pageInfo.pageNum + 1);
            });
            lastPageLi.click(function () {
                toPage(result.extend.pageInfo.pages)
            });
        }


        //添加首页和前一页
        ul.append(firstPageLi).append(prePageLi);
        $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {

            var numLi = $("<li></li>")
                .append($("<a></a>")
                    .append(item));
            //判断当前页就激活状态
            if (result.extend.pageInfo.pageNum == item) {
                numLi.addClass("active");
            }
            numLi.click(function () {
                toPage(item)
            });
            ul.append(numLi);
        });

        //添加末页和后一页
        ul.append(nextPageLi).append(lastPageLi);
        //创建导航条
        var navEle = $("<nav></nav>").append(ul);

        //添加到div中
        navEle.appendTo("#page_nav_area");

    }

    //显示分页信息
    function build_page_info(result) {

        $("#page_info_area").empty();
        $("#page_info_area").append("当前" + result.extend.pageInfo.pageNum + "页, 总共"
            + result.extend.pageInfo.pages + "页, 总共" + result.extend.pageInfo.total + "条记录数");
        totalRescord = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;
        totalPages = result.extend.pageInfo.pages;

    }

    //构建表格
    function build_emps_table(result) {
        //清空表格的信息
        $("#emps_table tbody").empty();
        var emps = result.extend.pageInfo.list;
        console.log(emps)
        $.each(emps, function (index, item) {
            var checkboxTd = $("<td><input type='checkbox' class='checkbox_item'/></td>");
            var userIdTd = $("<td></td>").append(item.id);
            var userNameTd = $("<td></td>").append(item.username);
            var emailTd = $("<td></td>").append(item.email);
            var phoneNumTd = $("<td></td>").append(item.phoneNum);
            var creditTd = $("<td></td>").append(item.credit);
            var statusTd = $("<td></td>").append(item.status == '1' ? "解除黑名单" : "黑名单");
            var typeTd = $("<td></td>").append(item.type == '1' ? "管理员" : "用户");
            var editBtn = $("<button></button>")
                .addClass("btn btn-success btn-sm edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil"))
                .append("编辑");
            //为每个员工编辑按钮添加id属性
            editBtn.attr("edit-id", item.id);
            var delBtn = $("<button></button>")
                .addClass("btn btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash"))
                .append("删除");
            //为每个员工删除按钮添加id属性
            delBtn.attr("del-id", item.id);
            var btTd = $("<td></td>")
                .append(editBtn)
                .append(" ")
                .append(delBtn);

            $("<tr></tr>").append(checkboxTd)
                .append(userIdTd)
                .append(userNameTd)
                .append(emailTd)
                .append(phoneNumTd)
                .append(creditTd)
                .append(statusTd)
                .append(typeTd)
                .append(btTd)
                .appendTo("#emps_table tbody");
        });
    }

    //点击编辑按钮弹出模态框
    $(document).on("click", ".edit_btn", function () {
        //查出用户基本信息显示用户名和邮箱和性别
        getUser($(this).attr("edit-id"));
        //查出部门信息
        //为更新按钮添加id属性
        $("#emp_update_btn").attr("edit-id", $(this).attr("edit-id"))
        // getDepts("#dept_update_select");
        $("#empUpdateModal").modal();
    });

    //为更新按钮添加事件
    $("#emp_update_btn").click(function () {

        //检验邮箱格式是否正确
        var email = $("#email_update_input").val();
        var reEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!reEmail.test(email)) {
            show_validate_msg("#email_update_input", "error", "邮箱格式有错！");
            return false;
        } else {
            show_validate_msg("#email_update_input", "success", "");
        }
        $.ajax({
            url: "/user/update/" + $(this).attr("edit-id"),
            type: "POST",
            data: $("#from_modal_update").serialize(),
            success: function (result) {
                if (result.code == 100) {
                    //1.关闭模态框
                    $("#empUpdateModal").modal('hide');
                    //2.跳转到最后一页显示刚插入的数据
                    toPage(currentPage);
                } else {

                }

            }
        })
    });

    $("#emp_add_modal_btn").click(function () {
        //表单重置
        // $("#from_modal_add")[0].reset();
        reset_from("#from_modal_add");
        // getDepts("#dept_add_select");
        $("#empAddModal").modal();
    });

    //获取用户信息
    function getUser(id) {
        $.ajax({
            url: "/get/user?id=" + id,
            type: "GET",
            success: function (result) {
                //处理成功后操作
                var user = result.extend.currentUser;
                console.log(user)
                $("#empName_static_p").text(user.username);
                $("#password_update_input").text([user.password]);
                $("#email_update_input").val([user.email]);
                $("#phone_update_input").val([user.phoneNum]);
                $("#credit_update_input").val([user.credit]);
                $("#empUpdateModal input[name=type]").val([user.type]);
                $("#empUpdateModal input[name=status]").val([user.status]);
            }
        });
    }

    //表单清空样式和内容
    function reset_from(ele) {
        $(ele)[0].reset();
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
    }

    //点击删除按钮删除删除员工
    $(document).on("click", ".delete_btn", function () {
        //寻找当前元素的父类下的第二个元素的值
        var userName = $(this).parents("tr").find("td:eq(2)").text();
        if (confirm("确认删除【" + userName + "】吗？")) {
            $.ajax({
                url: "/user/delete/" + $(this).attr("del-id"),
                type: "DELETE",
                success: function (result) {
                    toPage(currentPage);
                }
            });
        }
    });

    //保存员工
    $("#emp_save_btn").click(function () {
        //校验表单数据方法
        if (!validate_add_form()) {
            return false;
        }
        if ($(this).attr("ajax_va") == "error") {
            return false;
        }
        $.ajax({
            url: "/user/add",
            type: "POST",
            data: $("#from_modal_add").serialize(),
            success: function (result) {
                if (result.code == 100) {
                    //1.关闭模态框
                    $("#empAddModal").modal('hide');
                    //2.跳转到最后一页显示刚插入的数据
                    toPage(totalPages);
                } else {

                }

            }
        })

    });

    //保存表单检验
    function validate_add_form() {

        var empName = $("#empName_add_input").val();
        var reName = /(^[a-zA-Z0-9_-]{5,16}$)|(^[\u2E80-\u9FFF]{2,6})/;

        if (!reName.test(empName)) {
            show_validate_msg("#empName_add_input", "error", "用户名只支持2-6位的中文或者5到16位的英文字符！");
            return false;
        } else {
            show_validate_msg("#empName_add_input", "success", "");
        }

        var email = $("#email_add_input").val();
        var reEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!reEmail.test(email)) {
            show_validate_msg("#email_add_input", "error", "邮箱格式有错！");
            return false;
        } else {
            show_validate_msg("#email_add_input", "success", "");
        }

        return true;
    }

    //显示校验提示信息
    function show_validate_msg(element, status, message) {

        $(element).parent().removeClass("has-success has-error");
        $(element).next("span").text(message);

        if ("success" == status) {
            $(element).parent().addClass("has-success");
            $(element).next("span").text(message);
        } else if ("error" == status) {
            $(element).parent().addClass("has-error");
            $(element).next("span").text(message);
        }
    }

    //为单选框绑定点击事件
    $("#checkbox_all").click(function () {
        $(".checkbox_item").prop("checked", $(this).prop("checked"));
    });

    //为子单选框绑定点击事件
    $(document).on("click", ".checkbox_item", function () {
        //设置与子选框的状态一致
        $("#checkbox_all").prop("checked",
            $(".checkbox_item:checked").length == $(".checkbox_item").length);
    });

    //批量删除按钮绑定点击事件
    $("#emp_delete_btn").click(function () {
        var userNames = "";
        var del_idstr = "";
        $.each($(".checkbox_item:checked"), function () {
            userNames += $(this).parents("tr").find("td:eq(2)").text() + ",";
            del_idstr += $(this).parents("tr").find("td:eq(1)").text() + "-";
        })
        userNames = userNames.substring(0, userNames.length - 1);
        del_idstr = del_idstr.substring(0, del_idstr.length - 1);

        if (confirm("确认删除【" + userNames + "】吗？")) {
            $.ajax({
                url: "/user/delete/" + del_idstr,
                type: "DELETE",
                success: function (result) {
                    alert(result.msg);
                    toPage(totalPages);
                }
            });
        }
    });

    /**
     *  此方法为切换左边菜单的js文件
     */
    $(".list_dt").on("click", function () {
        $('.list_dd').stop();
        $(this).siblings("dt").removeAttr("id");
        if ($(this).attr("id") == "open") {
            $(this).removeAttr("id").siblings("dd").slideUp();
        } else {
            $(this).attr("id", "open").next().slideDown().siblings("dd").slideUp();
        }
    });

    /**
     * 退出登录
     */
    function signout_confirm() {
        var r = confirm("确定退出?")
        if (r == true) {
            window.location.href = "/signout";
        } else {

        }
    }

    function toPage(pn) {

        $.ajax({
            url: "/get/users",
            data: "pn=" + pn,
            type: "GET",
            success: function (result) {
                build_emps_table(result);
                build_page_info(result);
                build_page_nav(result);
            }
        });
    }

    $("#search").on("click", function () {
        var username = $("#searchName").val();
        $.ajax({
            url: "/user/query/" + username,
            type: "GET",
            success: function (result) {
                build_emps_table(result);
                build_page_info(result);
                build_page_nav(result);
            }
        });
    })

</script>

</body>

</html>